var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var jwt = require('jsonwebtoken');
let { customModel } = require('./model/model');

let indexRouter = require('./routes/index');
let usersRouter = require('./routes/users');
let loginRouter = require('./routes/login');
let personRouter = require('./routes/personal');
let chatRouter = require('./routes/chat');
let homepageRouter = require('./routes/homepage');
let mapRouter = require('./routes/map');

var app = express();

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.use((req, res, next) => {
  let pathArr = [
    '/login/userLogin',
    '/login/refresh',
    '/login/faceLogin',
    '/login/sms',
    '/login/sendMail',
    '/login/addUser',
    '/login/forgetPassword',
    '/login/resetPassword',
    '/login/otherLogin',
    '/login/auth/weibo/callback',
  ];
  if (pathArr.includes(req.path)) {
    return next();
  }
  const accessToken = req.headers.accesstoken;
  const refreshToken = req.headers.refreshtoken;
  // 判断refreshToken是否过期
  try {
    jwt.verify(refreshToken, 'LIXIANGYU');
  } catch (error) {
    console.log(error);
    return res.status(403).send({ message: 'Forbidden' });
  }
  if (!accessToken) {
    return res.status(401).send({ message: 'Unauthorized' });
  }
  try {
    const user = jwt.verify(accessToken, 'LIXIANGYU');
    res.locals.user = user;
    return next();
  } catch (error) {
    return res.status(401).send({ message: 'Unauthorized' });
  }
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/upload', express.static(path.join(__dirname, 'upload')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/login', loginRouter);
app.use('/chat', chatRouter);
app.use('/homepage', homepageRouter);
app.use('/personal', personRouter);
app.use('/map', mapRouter);
const { log } = require('console');
const { createServer } = require('http');
const httpServer = createServer();
const io = require('socket.io')(httpServer, {
  cors: { origin: '*' },
});

// io.on('connection', (socket) => {
//   console.log('A user connected:', socket.id);

//   // 注册用户连接
//   socket.on('register', async (userId) => {
//     // bug写一个单设备登录
//     console.log(userId,'userId');
//     try {
//       if (!userId) {
//         console.error('Invalid userId:', userId);
//         return;
//       }
//       // 更新或创建用户的 socketId
//       await customModel.findOneAndUpdate(
//         { userId },
//         { socketId: socket.id },
//         { upsert: true }
//       );
//       console.log(`User ${userId} registered with socket ID ${socket.id}`);
//     } catch (err) {
//       console.error('Error registering user:', err);
//     }
//   });

//   // 处理消息发送
//   socket.on('sendMessage', async (data) => {
//     const { toUserId, message } = data;
//     message._id = Date.now();
//     console.log(message,'message');

//     try {
//       const user = await customModel.findOne({ userId: toUserId });
//       if (user) {
//         io.to(user.socketId).emit('message', message);
//         console.log(`Message sent to user ${toUserId}: ${message}`);
//       } else {
//         console.log(`User ${toUserId} not found`);
//       }
//     } catch (err) {
//       console.error('Error sending message:', err);
//     }
//   });

//   // 处理断开连接
//   socket.on('disconnect', async () => {
//     console.log('User disconnected:', socket.id);
//     try {
//       await customModel.findOneAndUpdate(
//         { socketId: socket.id },
//         { socketId: null }
//       );
//     } catch (err) {
//       console.error('Error updating user on disconnect:', err);
//     }
//   });
// });

// httpServer.listen(4000, () => {
//   console.log(4000, '监听已开始');
// });

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  console.log(err.message);
  // res.locals.message = err.message;
  // res.locals.error = req.app.get('env') === 'development' ? err : {};

  // // render the error page
  // res.status(err.status || 500);
  // res.render('error');
});

module.exports = app;
